package com.weijian.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weijian.common.pojo.CommonResult;
import com.weijian.common.pojo.PageResponse;
import com.weijian.dal.dto.OrderFormDTO;
import com.weijian.dal.entity.Address;
import com.weijian.dal.entity.Order;
import com.weijian.dal.entity.User;
import com.weijian.dal.query.OrderPageQuery;
import com.weijian.dal.vo.OrderStatisticsVO;
import com.weijian.dal.vo.OrderVO;
import com.weijian.service.AddressService;
import com.weijian.service.OrderService;
import com.weijian.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
@Slf4j
public class OrderController {

    private final OrderService orderService;

    private final AddressService addressService;

    private final UserService userService;


    @Operation(summary = "分页查询订单")
    @PostMapping("/list")
    public PageResponse<OrderVO> queryOrderByPage(@RequestBody OrderPageQuery query) {
        // 查询订单分页数据
        Page<Order> orderPage = orderService.lambdaQuery()
                .eq(StrUtil.isNotBlank(query.getNumber()), Order::getNumber, query.getNumber())
                .eq(Order::getStatus, query.getStatus())
                .between(query.getBeginTime() != null, Order::getCreateTime, query.getBeginTime(), query.getEndTime())
                .page(query.toMpPage("update_time", false));

        List<Order> orders = orderPage.getRecords();
        if (orders.isEmpty()) {
            return PageResponse.empty(orderPage);
        }
        // 提取 addressId 和 userId 列表
        Set<Long> addressIds = orders.stream()
                .map(Order::getAddressId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Set<Long> userIds = orders.stream()
                .map(Order::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        // 批量查询地址和用户信息
        Map<Long, Address> addressMap = addressService.listByIds(addressIds).stream()
                .collect(Collectors.toMap(Address::getId, a -> a));
        Map<Long, User> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, u -> u));
        log.info(userMap.toString());
        // 自定义转换逻辑
        Function<Order, OrderVO> convertor = order -> {
            OrderVO orderVO = BeanUtil.copyProperties(order, OrderVO.class);
            // 填充地址信息
            if (order.getAddressId() != null && addressMap.containsKey(order.getAddressId())) {
                Address address = addressMap.get(order.getAddressId());
                String detailAddress = Optional.ofNullable(address.getProvince()).orElse("") +
                        Optional.ofNullable(address.getCity()).orElse("") +
                        Optional.ofNullable(address.getTown()).orElse("") +
                        Optional.ofNullable(address.getDetail()).orElse("");
                orderVO.setAddress(detailAddress);
            }
            // 填充用户信息
            if (order.getUserId() != null && userMap.containsKey(order.getUserId())) {
                User user = userMap.get(order.getUserId());
                orderVO.setUserName(Optional.ofNullable(user.getUserName()).orElse(""));
                orderVO.setPhone(Optional.ofNullable(user.getPhone()).orElse(""));
            }
            return orderVO;
        };
        // 使用自定义转换器构建分页响应
        return PageResponse.of(orderPage, convertor);
    }


    @Operation(summary = "根据id查询订单")
    @GetMapping("{id}")
    public OrderVO queryOrderById(@Param("订单id") @PathVariable("id") Long id) {
        try {
            Order order = orderService.getById(id);
            OrderVO orderVO = BeanUtil.copyProperties(order, OrderVO.class);
            Address address = addressService.getById(order.getAddressId());
            String detailAddress = address.getProvince() + address.getCity() + address.getTown() + address.getDetail();
            String userName = userService.getById(order.getUserId()).getUserName();
            String phone = userService.getById(order.getUserId()).getPhone();
            log.info("订单详情：{}", orderVO);
            orderVO.setUserName(userName);
            orderVO.setAddress(detailAddress);
            orderVO.setPhone(phone);
            return orderVO;
        } catch (Exception e) {
            log.info("查询订单失败", e);
            throw new RuntimeException(e);
        }
    }

    @Operation(summary = "创建订单")
    @PostMapping
    public Long createOrder(@RequestBody OrderFormDTO orderFormDTO) {
        return orderService.createOrder(orderFormDTO);
    }

    @Operation(summary = "修改订单转态")
    @PutMapping("/status/{id}/{status}")
    public void updateOrderStatus(@PathVariable(value = "id") Long id, @PathVariable(value = "status") Integer status) {
        orderService.updateOrderStatus(id, status);
    }

    @Operation(summary = "根据id删除订单")
    @DeleteMapping("/{id}")
    public void deleteOrderById(@PathVariable("id") Long id) {
        orderService.removeById(id);
    }

    @GetMapping("/statistics")
    @Operation(description = "各个状态的订单数量统计")
    public CommonResult<OrderStatisticsVO> statistics() {
        OrderStatisticsVO orderStatisticsVO = orderService.statistics();
        return CommonResult.success(orderStatisticsVO);
    }


}
